<template>
  <transition name="el-zoom-in-center">
    <div v-if="visible" class="cu-preview-main">
      <div class="cu-common-page-header">
        <el-page-header @back="visible = false" :content="`${overviewData.trainName || ''} - 签到状态概览`" />
        <div class="options">
          <el-button type="primary" icon="el-icon-refresh" @click="handleRefresh" :loading="loading">刷新数据</el-button>
        </div>
      </div>
      <div class="cu-common-layout" v-loading="loading">
        <div class="cu-common-layout-center">
          <div class="cu-common-layout-main cu-flex-main">
            <!-- 基础统计卡片 -->
            <div class="stats-cards">
              <div class="stat-card total">
                <div class="stat-icon">
                  <i class="el-icon-user"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ overviewData.totalCount || 0 }}</div>
                  <div class="stat-label">总人数</div>
                </div>
              </div>

              <div class="stat-card signed">
                <div class="stat-icon">
                  <i class="el-icon-check"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ overviewData.signedCount || 0 }}</div>
                  <div class="stat-label">已签到</div>
                </div>
              </div>

              <div class="stat-card unsigned">
                <div class="stat-icon">
                  <i class="el-icon-close"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ overviewData.unsignedCount || 0 }}</div>
                  <div class="stat-label">未签到</div>
                </div>
              </div>

              <div class="stat-card rate">
                <div class="stat-icon">
                  <i class="el-icon-pie-chart"></i>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ overviewData.signRate || '0.00' }}%</div>
                  <div class="stat-label">签到率</div>
                </div>
              </div>
            </div>
            <!-- 详细统计表格 -->
            <div class="detail-section" v-if="detailData">
              <el-tabs v-model="activeTab" type="card">
                <!-- 按校区统计 -->
                <el-tab-pane label="按校区统计" name="campus">
                  <custom-table :data="paginatedCampusData" border stripe>
                    <el-table-column prop="campusName" label="校区" width="200" />
                    <el-table-column prop="totalCount" label="总人数" width="100" align="center" />
                    <el-table-column prop="signedCount" label="已签到" width="100" align="center">
                      <template slot-scope="scope">
                        <span class="signed-count">{{ scope.row.signedCount }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="unsignedCount" label="未签到" width="100" align="center">
                      <template slot-scope="scope">
                        <span class="unsigned-count">{{ scope.row.unsignedCount }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="signRate" label="签到率" width="120" align="center">
                      <template slot-scope="scope">
                        <el-progress :percentage="parseFloat(scope.row.signRate || 0)" :color="getProgressColor(parseFloat(scope.row.signRate || 0))" :show-text="false" :stroke-width="8" />
                        <span class="rate-text">{{ scope.row.signRate || '0.00' }}%</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="状态分布" min-width="200">
                      <template slot-scope="scope">
                        <div class="status-distribution">
                          <span class="status-item normal" v-if="scope.row.normalCount > 0">正常: {{ scope.row.normalCount }}</span>
                          <span class="status-item late" v-if="scope.row.lateCount > 0">迟到: {{ scope.row.lateCount }}</span>
                          <span class="status-item absent" v-if="scope.row.absentCount > 0">缺勤: {{ scope.row.absentCount }}</span>
                          <span class="status-item leave" v-if="scope.row.leaveCount > 0">请假: {{ scope.row.leaveCount }}</span>
                        </div>
                      </template>
                    </el-table-column>
                  </custom-table>
                  <div style="margin-top: 20px; text-align: right;">
                    <el-pagination @current-change="handleCampusPageChange" @size-change="size => handleSizeChange('campus', size)" :current-page="pagination.campus.currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="pagination.campus.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.campus.total"></el-pagination>
                  </div>
                </el-tab-pane>

                <!-- 按时间段统计 -->
                <el-tab-pane label="按时间段统计" name="timeslot">
                  <custom-table :data="paginatedTimeSlotData" border stripe>
                    <el-table-column prop="period" label="时间段" width="150" align="center">
                      <template slot-scope="scope">
                        <el-tag :type="getPeriodTagType(scope.row.period)">{{ getPeriodLabel(scope.row.period) }}</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="totalCount" label="总人数" width="100" align="center" />
                    <el-table-column prop="signedCount" label="已签到" width="100" align="center">
                      <template slot-scope="scope">
                        <span class="signed-count">{{ scope.row.signedCount }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="unsignedCount" label="未签到" width="100" align="center">
                      <template slot-scope="scope">
                        <span class="unsigned-count">{{ scope.row.unsignedCount }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="signRate" label="签到率" width="120" align="center">
                      <template slot-scope="scope">
                        <el-progress :percentage="parseFloat(scope.row.signRate || 0)" :color="getProgressColor(parseFloat(scope.row.signRate || 0))" :show-text="false" :stroke-width="8" />
                        <span class="rate-text">{{ scope.row.signRate || '0.00' }}%</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="状态分布" min-width="200">
                      <template slot-scope="scope">
                        <div class="status-distribution">
                          <span class="status-item normal" v-if="scope.row.normalCount > 0">正常: {{ scope.row.normalCount }}</span>
                          <span class="status-item late" v-if="scope.row.lateCount > 0">迟到: {{ scope.row.lateCount }}</span>
                          <span class="status-item absent" v-if="scope.row.absentCount > 0">缺勤: {{ scope.row.absentCount }}</span>
                          <span class="status-item leave" v-if="scope.row.leaveCount > 0">请假: {{ scope.row.leaveCount }}</span>
                        </div>
                      </template>
                    </el-table-column>
                  </custom-table>
                  <div style="margin-top: 20px; text-align: right;">
                    <el-pagination @current-change="handleTimeSlotPageChange" @size-change="size => handleSizeChange('timeslot', size)" :current-page="pagination.timeslot.currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="pagination.timeslot.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.timeslot.total"></el-pagination>
                  </div>
                </el-tab-pane>

                <!-- 教师详细统计 -->
                <el-tab-pane label="详细签到表格" name="detail">
                  <custom-table :data="paginatedTeacherData" border stripe>
                    <el-table-column prop="groupName" label="组别" width="120" align="center" />
                    <el-table-column prop="campusName" label="校区" width="150" align="center" />
                    <el-table-column prop="teacherName" label="老师姓名" width="120" align="center" />
                    <el-table-column v-for="date in detailData.dateColumns || []" :key="date.date" :label="date.label" align="center" min-width="180">
                      <template slot="header" slot-scope="scope">
                        <div class="date-header">
                          <div class="date-title">{{ date.label }}</div>
                          <div class="period-labels">
                            <span class="period-label">上午</span>
                            <span class="period-label">下午</span>
                            <span class="period-label" v-if="date.hasEvening">晚上</span>
                          </div>
                        </div>
                      </template>
                      <template slot-scope="scope">
                        <div class="sign-status-row">
                          <div class="status-cell">
                            <el-tag v-if="getSignStatus(scope.row, date.date, 'AM')" :type="getStatusTagType(getSignStatus(scope.row, date.date, 'AM'))" size="mini">
                              {{ getStatusLabel(getSignStatus(scope.row, date.date, 'AM')) }}
                            </el-tag>
                            <span v-else class="no-sign">-</span>
                          </div>
                          <div class="status-cell">
                            <el-tag v-if="getSignStatus(scope.row, date.date, 'PM')" :type="getStatusTagType(getSignStatus(scope.row, date.date, 'PM'))" size="mini">
                              {{ getStatusLabel(getSignStatus(scope.row, date.date, 'PM')) }}
                            </el-tag>
                            <span v-else class="no-sign">-</span>
                          </div>
                          <div class="status-cell" v-if="date.hasEvening">
                            <el-tag v-if="getSignStatus(scope.row, date.date, 'EVE')" :type="getStatusTagType(getSignStatus(scope.row, date.date, 'EVE'))" size="mini">
                              {{ getStatusLabel(getSignStatus(scope.row, date.date, 'EVE')) }}
                            </el-tag>
                            <span v-else class="no-sign">-</span>
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                  </custom-table>
                  <div style="margin-top: 20px; text-align: right;">
                    <el-pagination @current-change="handleDetailPageChange" @size-change="size => handleSizeChange('detail', size)" :current-page="pagination.detail.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.detail.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.detail.total"></el-pagination>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
import { getTrainSignOverview, getTrainSignDetailStatistics } from '@/api/campus/trainSignRecord'

export default {
  name: 'SignOverviewDialog',
  data() {
    return {
      visible: false,
      loading: false,
      trainId: '',
      activeTab: 'campus',
      overviewData: {},
      detailData: null,
      // 分页相关数据
      pagination: {
        campus: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        timeslot: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        detail: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      }
    }
  },
  computed: {
    // 校区统计分页数据
    paginatedCampusData() {
      if (!this.detailData || !this.detailData.campusStatistics) return []
      const start = (this.pagination.campus.currentPage - 1) * this.pagination.campus.pageSize
      const end = start + this.pagination.campus.pageSize
      return this.detailData.campusStatistics.slice(start, end)
    },
    // 时间段统计分页数据
    paginatedTimeSlotData() {
      if (!this.detailData || !this.detailData.timeSlotStatistics) return []
      const start = (this.pagination.timeslot.currentPage - 1) * this.pagination.timeslot.pageSize
      const end = start + this.pagination.timeslot.pageSize
      return this.detailData.timeSlotStatistics.slice(start, end)
    },
    // 教师详细统计分页数据
    paginatedTeacherData() {
      if (!this.detailData || !this.detailData.teacherDetailStatistics) return []
      const start = (this.pagination.detail.currentPage - 1) * this.pagination.detail.pageSize
      const end = start + this.pagination.detail.pageSize
      return this.detailData.teacherDetailStatistics.slice(start, end)
    }
  },
  methods: {
    init(trainId) {
      this.trainId = trainId
      this.visible = true
      this.activeTab = 'campus'
      this.loadData()
    },

    async loadData() {
      if (!this.trainId) {
        this.$message.warning('请先选择师训项目')
        return
      }

      this.loading = true
      try {
        // 并行加载概览数据和详细统计数据
        const [overviewRes, detailRes] = await Promise.all([getTrainSignOverview(this.trainId), getTrainSignDetailStatistics(this.trainId, {})])

        console.log('API响应数据:', { overviewRes, detailRes })

        // 使用后端统一的小写属性名格式
        const overviewRawData = overviewRes.data || {}
        this.overviewData = {
          totalCount: overviewRawData.totalCount || 0,
          signedCount: overviewRawData.signedCount || 0,
          unsignedCount: overviewRawData.unsignedCount || 0,
          signRate: overviewRawData.signRate || 0,
          trainName: overviewRawData.trainName || '',
          startTime: overviewRawData.startTime,
          endTime: overviewRawData.endTime,
          status: overviewRawData.status
        }

        // 使用后端统一的小写属性名格式
        const detailRawData = detailRes.data || null
        if (detailRawData) {
          // 处理教师详细统计数据
          const teacherDetailStatistics = (detailRawData.teacherStatistics || []).map(item => ({
            teacherId: item.teacherId,
            teacherName: item.teacherName,
            campusId: item.campusId,
            campusName: item.campusName,
            groupName: item.groupName,
            signRecords: item.signRecords
          }))

          // 处理日期列数据
          const dateColumns = (detailRawData.dateColumns || []).map(item => ({
            date: item.date,
            label: item.label || item.date.substring(5).replace('-', '月') + '日',
            hasEvening: item.hasEvening,
            timeSlots: item.timeSlots || []
          }))

          // 基于教师数据计算校区统计
          const campusStatistics = this.calculateCampusStatistics(teacherDetailStatistics, dateColumns)

          // 基于教师数据计算时间段统计
          const timeSlotStatistics = this.calculateTimeSlotStatistics(teacherDetailStatistics, dateColumns)

          this.detailData = {
            trainId: detailRawData.trainId,
            trainName: detailRawData.trainName,
            campusStatistics,
            timeSlotStatistics,
            teacherDetailStatistics,
            dateColumns
          }

          // 设置分页总数
          this.pagination.campus.total = this.detailData.campusStatistics.length
          this.pagination.timeslot.total = this.detailData.timeSlotStatistics.length
          this.pagination.detail.total = this.detailData.teacherDetailStatistics.length
        } else {
          this.detailData = null
        }

        console.log('处理后的数据:', { overviewData: this.overviewData, detailData: this.detailData })
      } catch (error) {
        console.error('加载签到概览数据失败:', error)
        this.$message.error('加载签到概览数据失败，请重试')
      } finally {
        this.loading = false
      }
    },

    handleRefresh() {
      this.loadData()
    },

    getProgressColor(percentage) {
      if (percentage >= 90) return '#67c23a'
      if (percentage >= 70) return '#e6a23c'
      return '#f56c6c'
    },

    getPeriodLabel(period) {
      const periodMap = {
        Morning: '上午',
        Afternoon: '下午',
        Evening: '晚上',
        AllDay: '全天'
      }
      return periodMap[period] || period
    },

    getPeriodTagType(period) {
      const typeMap = {
        Morning: 'success',
        Afternoon: 'warning',
        Evening: 'info',
        AllDay: 'primary'
      }
      return typeMap[period] || 'default'
    },

    // 获取指定老师、日期、时段的签到状态
    getSignStatus(teacher, date, period) {
      if (!teacher.signRecords || !teacher.signRecords[date]) {
        return null
      }
      return teacher.signRecords[date][period] || null
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        Normal: 'success', // 正常
        Late: 'warning', // 迟到
        Absent: 'danger', // 缺勤
        Leave: 'info' // 请假
      }
      return typeMap[status] || 'default'
    },

    // 获取状态标签文本
    getStatusLabel(status) {
      const labelMap = {
        Normal: '正常',
        Late: '迟到',
        Absent: '缺勤',
        Leave: '请假'
      }
      return labelMap[status] || status
    },

    // 处理校区统计分页变化
    handleCampusPageChange(page) {
      this.pagination.campus.currentPage = page
    },

    // 处理时间段统计分页变化
    handleTimeSlotPageChange(page) {
      this.pagination.timeslot.currentPage = page
    },

    // 处理教师详细统计分页变化
    handleDetailPageChange(page) {
      this.pagination.detail.currentPage = page
    },

    // 处理每页显示数量变化
    handleSizeChange(type, size) {
      this.pagination[type].pageSize = size
      this.pagination[type].currentPage = 1
    },

    // 计算校区统计数据
    calculateCampusStatistics(teacherDetailStatistics, dateColumns) {
      const campusMap = new Map()

      // 遍历所有教师数据
      teacherDetailStatistics.forEach(teacher => {
        const campusKey = `${teacher.campusId}_${teacher.campusName}`

        if (!campusMap.has(campusKey)) {
          campusMap.set(campusKey, {
            campusId: teacher.campusId,
            campusName: teacher.campusName,
            totalCount: 0,
            signedCount: 0,
            normalCount: 0,
            lateCount: 0,
            absentCount: 0,
            leaveCount: 0
          })
        }

        const campusData = campusMap.get(campusKey)
        campusData.totalCount++

        // 统计该教师的签到情况
        let hasAnySign = false
        dateColumns.forEach(dateCol => {
          const dateRecords = teacher.signRecords && teacher.signRecords[dateCol.date]
          if (dateRecords) {
            Object.values(dateRecords).forEach(status => {
              if (status) {
                hasAnySign = true
                switch (status) {
                  case 'Normal':
                    campusData.normalCount++
                    break
                  case 'Late':
                    campusData.lateCount++
                    break
                  case 'Absent':
                    campusData.absentCount++
                    break
                  case 'Leave':
                    campusData.leaveCount++
                    break
                }
              }
            })
          }
        })

        if (hasAnySign) {
          campusData.signedCount++
        }
      })

      // 计算签到率并转换为数组
      return Array.from(campusMap.values()).map(campus => {
        campus.unsignedCount = campus.totalCount - campus.signedCount
        campus.signRate = campus.totalCount > 0 ? ((campus.signedCount / campus.totalCount) * 100).toFixed(2) : '0.00'
        return campus
      })
    },

    // 计算时间段统计数据
    calculateTimeSlotStatistics(teacherDetailStatistics, dateColumns) {
      const periodMap = new Map()

      // 初始化时间段统计
      const periods = ['AM', 'PM', 'EVE']
      const periodLabels = { AM: 'Morning', PM: 'Afternoon', EVE: 'Evening' }

      periods.forEach(period => {
        periodMap.set(period, {
          period: periodLabels[period],
          totalCount: 0,
          signedCount: 0,
          normalCount: 0,
          lateCount: 0,
          absentCount: 0,
          leaveCount: 0
        })
      })

      // 遍历所有教师和日期
      teacherDetailStatistics.forEach(teacher => {
        dateColumns.forEach(dateCol => {
          const dateRecords = teacher.signRecords && teacher.signRecords[dateCol.date]
          if (dateRecords) {
            periods.forEach(period => {
              const periodData = periodMap.get(period)
              periodData.totalCount++

              const status = dateRecords[period]
              if (status) {
                periodData.signedCount++
                switch (status) {
                  case 'Normal':
                    periodData.normalCount++
                    break
                  case 'Late':
                    periodData.lateCount++
                    break
                  case 'Absent':
                    periodData.absentCount++
                    break
                  case 'Leave':
                    periodData.leaveCount++
                    break
                }
              }
            })
          }
        })
      })

      // 计算签到率并转换为数组
      return Array.from(periodMap.values())
        .map(period => {
          period.unsignedCount = period.totalCount - period.signedCount
          period.signRate = period.totalCount > 0 ? ((period.signedCount / period.totalCount) * 100).toFixed(2) : '0.00'
          return period
        })
        .filter(period => period.totalCount > 0) // 只返回有数据的时间段
    },

    close() {
      this.visible = false
      this.trainId = ''
      this.activeTab = 'campus'
      this.overviewData = {}
      this.detailData = null
      // 重置分页
      this.pagination.campus.currentPage = 1
      this.pagination.timeslot.currentPage = 1
      this.pagination.detail.currentPage = 1
    }
  }
}
</script>

<style lang="scss" scoped>
.cu-common-page-header {
  flex-shrink: 0;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.cu-common-layout {
  flex: 1;
  height: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.cu-common-layout-center {
  flex: 1;
  height: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.cu-common-layout-main {
  flex: 1;
  height: 0;
  overflow: auto;
  padding: 20px;
  background: #fff;
}

.overview-container {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  min-height: 400px;
}

.stats-cards {
  flex-shrink: 0;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;

  .stat-card {
    display: flex;
    align-items: center;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s;

    &:hover {
      transform: translateY(-2px);
    }

    .stat-icon {
      font-size: 32px;
      margin-right: 15px;
      width: 50px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
    }

    .stat-content {
      flex: 1;

      .stat-number {
        font-size: 28px;
        font-weight: bold;
        line-height: 1;
        margin-bottom: 5px;
      }

      .stat-label {
        font-size: 14px;
        color: #666;
      }
    }

    &.total {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;

      .stat-icon {
        background: rgba(255, 255, 255, 0.2);
      }
    }

    &.signed {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      color: white;

      .stat-icon {
        background: rgba(255, 255, 255, 0.2);
      }
    }

    &.unsigned {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: white;

      .stat-icon {
        background: rgba(255, 255, 255, 0.2);
      }
    }

    &.rate {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      color: white;

      .stat-icon {
        background: rgba(255, 255, 255, 0.2);
      }
    }
  }
}

.detail-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 0;
  overflow: hidden;

  .el-tabs {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 0;
    overflow: hidden;

    ::v-deep .el-tabs__content {
      flex: 1;
      height: 0;
      overflow: hidden;

      .el-tab-pane {
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .custom-table {
          flex: 1;
          height: 0;
          overflow: auto;
        }

        .el-pagination {
          flex-shrink: 0;
          margin-top: 20px;
          text-align: right;
        }
      }
    }
  }

  .rate-text {
    margin-left: 10px;
    font-weight: bold;
  }

  .signed-count {
    color: #67c23a;
    font-weight: bold;
  }

  .unsigned-count {
    color: #f56c6c;
    font-weight: bold;
  }

  .status-distribution {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .status-item {
      padding: 2px 8px;
      border-radius: 4px;
      font-size: 12px;

      &.normal {
        background: #f0f9ff;
        color: #67c23a;
        border: 1px solid #67c23a;
      }

      &.late {
        background: #fef7e0;
        color: #e6a23c;
        border: 1px solid #e6a23c;
      }

      &.absent {
        background: #fef0f0;
        color: #f56c6c;
        border: 1px solid #f56c6c;
      }

      &.leave {
        background: #f4f4f5;
        color: #909399;
        border: 1px solid #909399;
      }
    }
  }
}

// 详细签到表格样式
.date-header {
  text-align: center;

  .date-title {
    font-weight: bold;
    margin-bottom: 5px;
    font-size: 14px;
  }

  .period-labels {
    display: flex;
    justify-content: space-around;
    border-top: 1px solid #e4e7ed;
    padding-top: 5px;

    .period-label {
      font-size: 12px;
      color: #606266;
      font-weight: normal;
    }
  }
}

.sign-status-row {
  display: flex;
  justify-content: space-around;
  align-items: center;

  .status-cell {
    flex: 1;
    text-align: center;
    padding: 2px;

    .no-sign {
      color: #c0c4cc;
      font-size: 12px;
    }
  }
}
</style>
